home *** CD-ROM | disk | FTP | other *** search
/ Cream of the Crop 26 / Cream of the Crop 26.iso / os2 / octa209s.zip / octave-2.09 / libs / readline / history.c < prev    next >
C/C++ Source or Header  |  1996-11-01  |  57KB  |  2,281 lines

  1. /* Modified by Klaus Gebhardt, October 1996 */
  2. /* History.c -- standalone history library */
  3.  
  4. /* Copyright (C) 1989, 1992 Free Software Foundation, Inc.
  5.  
  6.    This file contains the GNU History Library (the Library), a set of
  7.    routines for managing the text of previously typed lines.
  8.  
  9.    The Library is free software; you can redistribute it and/or modify
  10.    it under the terms of the GNU General Public License as published by
  11.    the Free Software Foundation; either version 1, or (at your option)
  12.    any later version.
  13.  
  14.    The Library is distributed in the hope that it will be useful, but
  15.    WITHOUT ANY WARRANTY; without even the implied warranty of
  16.    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
  17.    General Public License for more details.
  18.  
  19.    The GNU General Public License is often shipped with GNU software, and
  20.    is generally kept in a file called COPYING or LICENSE.  If you do not
  21.    have a copy of the license, write to the Free Software Foundation,
  22.    675 Mass Ave, Cambridge, MA 02139, USA. */
  23.  
  24. /* The goal is to make the implementation transparent, so that you
  25.    don't have to know what data types are used, just what functions
  26.    you can call.  I think I have done that. */
  27.  
  28. #ifdef HAVE_CONFIG_H
  29. #include <config.h>
  30. #endif
  31.  
  32. #define READLINE_LIBRARY
  33.  
  34. #include <stdio.h>
  35. #include <sys/types.h>
  36. #include <sys/file.h>
  37. #include <sys/stat.h>
  38. #include <fcntl.h>
  39. #if defined (HAVE_STDLIB_H)
  40. #  include <stdlib.h>
  41. #else
  42. #  include "ansi_stdlib.h"
  43. #endif /* HAVE_STDLIB_H */
  44. #if defined (HAVE_UNISTD_H)
  45. #  include <unistd.h>
  46. #endif
  47. #if defined (HAVE_STRING_H)
  48. #  include <string.h>
  49. #else
  50. #  include <strings.h>
  51. #endif /* !HAVE_STRING_H */
  52. #include <errno.h>
  53.  
  54. /* Not all systems declare ERRNO in errno.h... and some systems #define it! */
  55. #if !defined (errno)
  56. extern int errno;
  57. #endif /* !errno */
  58.  
  59. #include "memalloc.h"
  60. #include "history.h"
  61.  
  62. #if defined (STATIC_MALLOC)
  63. static char *xmalloc (), *xrealloc ();
  64. #else
  65. extern char *xmalloc (), *xrealloc ();
  66. #endif /* STATIC_MALLOC */
  67.  
  68. #define STREQ(a, b)    (((a)[0] == (b)[0]) && (strcmp ((a), (b)) == 0))
  69. #define STREQN(a, b, n)    (((a)[0] == (b)[0]) && (strncmp ((a), (b), (n)) == 0))
  70.  
  71. #ifndef savestring
  72. #  ifndef strcpy
  73. extern char *strcpy ();
  74. #  endif
  75. #define savestring(x) strcpy (xmalloc (1 + strlen (x)), (x))
  76. #endif
  77.  
  78. #ifndef whitespace
  79. #define whitespace(c) (((c) == ' ') || ((c) == '\t'))
  80. #endif
  81.  
  82. #ifndef digit_p
  83. #define digit_p(c)  ((c) >= '0' && (c) <= '9')
  84. #endif
  85.  
  86. #ifndef digit_value
  87. #define digit_value(c) ((c) - '0')
  88. #endif
  89.  
  90. #ifndef member
  91. #  ifndef strchr
  92. extern char *strchr ();
  93. #  endif
  94. #define member(c, s) ((c) ? ((char *)strchr ((s), (c)) != (char *)NULL) : 0)
  95. #endif
  96.  
  97. /* Possible history errors passed to hist_error. */
  98. #define EVENT_NOT_FOUND 0
  99. #define BAD_WORD_SPEC    1
  100. #define SUBST_FAILED    2
  101. #define BAD_MODIFIER    3
  102.  
  103. static char error_pointer;
  104.  
  105. static char *subst_lhs;
  106. static char *subst_rhs;
  107. static int subst_lhs_len = 0;
  108. static int subst_rhs_len = 0;
  109.  
  110. static char *get_history_word_specifier ();
  111. static char *history_find_word ();
  112.  
  113. #if defined (SHELL)
  114. extern char *single_quote ();
  115. #endif
  116.  
  117. /* **************************************************************** */
  118. /*                                    */
  119. /*            History Functions                */
  120. /*                                    */
  121. /* **************************************************************** */
  122.  
  123. /* An array of HIST_ENTRY.  This is where we store the history. */
  124. static HIST_ENTRY **the_history = (HIST_ENTRY **)NULL;
  125.  
  126. /* Non-zero means that we have enforced a limit on the amount of
  127.    history that we save. */
  128. #if defined (__EMX__) && defined (OS2)
  129. int history_stifled = 0;
  130. #else
  131. static int history_stifled = 0;
  132. #endif
  133.  
  134. /* If HISTORY_STIFLED is non-zero, then this is the maximum number of
  135.    entries to remember. */
  136. int max_input_history;
  137.  
  138. /* The current location of the interactive history pointer.  Just makes
  139.    life easier for outside callers. */
  140. static int history_offset = 0;
  141.  
  142. /* The number of strings currently stored in the input_history list. */
  143. int history_length = 0;
  144.  
  145. /* The current number of slots allocated to the input_history. */
  146. static int history_size = 0;
  147.  
  148. /* The number of slots to increase the_history by. */
  149. #define DEFAULT_HISTORY_GROW_SIZE 50
  150.  
  151. /* The character that represents the start of a history expansion
  152.    request.  This is usually `!'. */
  153. char history_expansion_char = '!';
  154.  
  155. /* The character that invokes word substitution if found at the start of
  156.    a line.  This is usually `^'. */
  157. char history_subst_char = '^';
  158.  
  159. /* During tokenization, if this character is seen as the first character
  160.    of a word, then it, and all subsequent characters upto a newline are
  161.    ignored.  For a Bourne shell, this should be '#'.  Bash special cases
  162.    the interactive comment character to not be a comment delimiter. */
  163. char history_comment_char = '\0';
  164.  
  165. /* The list of characters which inhibit the expansion of text if found
  166.    immediately following history_expansion_char. */
  167. char *history_no_expand_chars = " \t\n\r=";
  168.  
  169. /* The logical `base' of the history array.  It defaults to 1. */
  170. int history_base = 1;
  171.  
  172. /* Return the current HISTORY_STATE of the history. */
  173. HISTORY_STATE *
  174. history_get_history_state ()
  175. {
  176.   HISTORY_STATE *state;
  177.  
  178.   state = (HISTORY_STATE *)xmalloc (sizeof (HISTORY_STATE));
  179.   state->entries = the_history;
  180.   state->offset = history_offset;
  181.   state->length = history_length;
  182.   state->size = history_size;
  183.   state->flags = 0;
  184.   if (history_stifled)
  185.     state->flags |= HS_STIFLED;
  186.  
  187.   return (state);
  188. }
  189.  
  190. /* Set the state of the current history array to STATE. */
  191. void
  192. history_set_history_state (state)
  193.      HISTORY_STATE *state;
  194. {
  195.   the_history = state->entries;
  196.   history_offset = state->offset;
  197.   history_length = state->length;
  198.   history_size = state->size;
  199.   if (state->flags & HS_STIFLED)
  200.     history_stifled = 1;
  201. }
  202.  
  203. /* Begin a session in which the history functions might be used.  This
  204.    initializes interactive variables. */
  205. void
  206. using_history ()
  207. {
  208.   history_offset = history_length;
  209. }
  210.  
  211. /* Return the number of bytes that the primary history entries are using.
  212.    This just adds up the lengths of the_history->lines. */
  213. int
  214. history_total_bytes ()
  215. {
  216.   register int i, result;
  217.  
  218.   result = 0;
  219.  
  220.   for (i = 0; the_history && the_history[i]; i++)
  221.     result += strlen (the_history[i]->line);
  222.  
  223.   return (result);
  224. }
  225.  
  226. /* Place STRING at the end of the history list.  The data field
  227.    is  set to NULL. */
  228. void
  229. add_history (string)
  230.      char *string;
  231. {
  232.   HIST_ENTRY *temp;
  233.  
  234.   if (history_stifled && (history_length == max_input_history))
  235.     {
  236.       register int i;
  237.  
  238.       /* If the history is stifled, and history_length is zero,
  239.      and it equals max_input_history, we don't save items. */
  240.       if (history_length == 0)
  241.     return;
  242.  
  243.       /* If there is something in the slot, then remove it. */
  244.       if (the_history[0])
  245.     {
  246.       free (the_history[0]->line);
  247.       free (the_history[0]);
  248.     }
  249.  
  250.       /* Copy the rest of the entries, moving down one slot. */
  251.       for (i = 0; i < history_length; i++)
  252.     the_history[i] = the_history[i + 1];
  253.  
  254.       history_base++;
  255.  
  256.     }
  257.   else
  258.     {
  259.       if (!history_size)
  260.     {
  261.       history_size = DEFAULT_HISTORY_GROW_SIZE;
  262.       the_history = (HIST_ENTRY **)xmalloc (history_size * sizeof (HIST_ENTRY *));
  263.       history_length = 1;
  264.  
  265.     }
  266.       else
  267.     {
  268.       if (history_length == (history_size - 1))
  269.         {
  270.           history_size += DEFAULT_HISTORY_GROW_SIZE;
  271.           the_history = (HIST_ENTRY **)
  272.         xrealloc (the_history, history_size * sizeof (HIST_ENTRY *));
  273.         }
  274.       history_length++;
  275.     }
  276.     }
  277.  
  278.   temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  279.   temp->line = savestring (string);
  280.   temp->data = (char *)NULL;
  281.  
  282.   the_history[history_length] = (HIST_ENTRY *)NULL;
  283.   the_history[history_length - 1] = temp;
  284. }
  285.  
  286. /* Make the history entry at WHICH have LINE and DATA.  This returns
  287.    the old entry so you can dispose of the data.  In the case of an
  288.    invalid WHICH, a NULL pointer is returned. */
  289. HIST_ENTRY *
  290. replace_history_entry (which, line, data)
  291.      int which;
  292.      char *line;
  293.      char *data;
  294. {
  295.   HIST_ENTRY *temp = (HIST_ENTRY *)xmalloc (sizeof (HIST_ENTRY));
  296.   HIST_ENTRY *old_value;
  297.  
  298.   if (which >= history_length)
  299.     return ((HIST_ENTRY *)NULL);
  300.  
  301.   old_value = the_history[which];
  302.  
  303.   temp->line = savestring (line);
  304.   temp->data = data;
  305.   the_history[which] = temp;
  306.  
  307.   return (old_value);
  308. }
  309.  
  310. /* Returns the magic number which says what history element we are
  311.    looking at now.  In this implementation, it returns history_offset. */
  312. int
  313. where_history ()
  314. {
  315.   return (history_offset);
  316. }
  317.  
  318. /* Search the history for STRING, starting at history_offset.
  319.    If DIRECTION < 0, then the search is through previous entries, else
  320.    through subsequent.  If ANCHORED is non-zero, the string must
  321.    appear at the beginning of a history line, otherwise, the string
  322.    may appear anywhere in the line.  If the string is found, then
  323.    current_history () is the history entry, and the value of this
  324.    function is the offset in the line of that history entry that the
  325.    string was found in.  Otherwise, nothing is changed, and a -1 is
  326.    returned. */
  327.  
  328. #define ANCHORED_SEARCH 1
  329. #define NON_ANCHORED_SEARCH 0
  330.  
  331. static int
  332. history_search_internal (string, direction, anchored)
  333.      char *string;
  334.      int direction, anchored;
  335. {
  336.   register int i, reverse;
  337.   register char *line;
  338.   register int line_index;
  339.   int string_len;
  340.  
  341.   i = history_offset;
  342.   reverse = (direction < 0);
  343.  
  344.   /* Take care of trivial cases first. */
  345.  
  346.   if (!history_length || ((i == history_length) && !reverse))
  347.     return (-1);
  348.  
  349.   if (reverse && (i == history_length))
  350.     i--;
  351.  
  352. #define NEXT_LINE() do { if (reverse) i--; else i++; } while (0)
  353.  
  354.   string_len = strlen (string);
  355.   while (1)
  356.     {
  357.       /* Search each line in the history list for STRING. */
  358.  
  359.       /* At limit for direction? */
  360.       if ((reverse && i < 0) || (!reverse && i == history_length))
  361.     return (-1);
  362.  
  363.       line = the_history[i]->line;
  364.       line_index = strlen (line);
  365.  
  366.       /* If STRING is longer than line, no match. */
  367.       if (string_len > line_index)
  368.     {
  369.       NEXT_LINE ();
  370.       continue;
  371.     }
  372.  
  373.       /* Handle anchored searches first. */
  374.       if (anchored == ANCHORED_SEARCH)
  375.     {
  376.       if (STREQN (string, line, string_len))
  377.         {
  378.           history_offset = i;
  379.           return (0);
  380.         }
  381.  
  382.       NEXT_LINE ();
  383.       continue;
  384.     }
  385.  
  386.       /* Do substring search. */
  387.       if (reverse)
  388.     {
  389.       line_index -= string_len;
  390.  
  391.       while (line_index >= 0)
  392.         {
  393.           if (STREQN (string, line + line_index, string_len))
  394.         {
  395.           history_offset = i;
  396.           return (line_index);
  397.         }
  398.           line_index--;
  399.         }
  400.     }
  401.       else
  402.     {
  403.       register int limit = line_index - string_len + 1;
  404.       line_index = 0;
  405.  
  406.       while (line_index < limit)
  407.         {
  408.           if (STREQN (string, line + line_index, string_len))
  409.         {
  410.           history_offset = i;
  411.           return (line_index);
  412.         }
  413.           line_index++;
  414.         }
  415.     }
  416.       NEXT_LINE ();
  417.     }
  418. }
  419.  
  420. /* Do a non-anchored search for STRING through the history in DIRECTION. */
  421. int
  422. history_search (string, direction)
  423.      char *string;
  424.      int direction;
  425. {
  426.   return (history_search_internal (string, direction, NON_ANCHORED_SEARCH));
  427. }
  428.  
  429. /* Do an anchored search for string through the history in DIRECTION. */
  430. int
  431. history_search_prefix (string, direction)
  432.      char *string;
  433.      int direction;
  434. {
  435.   return (history_search_internal (string, direction, ANCHORED_SEARCH));
  436. }
  437.  
  438. /* Remove history element WHICH from the history.  The removed
  439.    element is returned to you so you can free the line, data,
  440.    and containing structure. */
  441. HIST_ENTRY *
  442. remove_history (which)
  443.      int which;
  444. {
  445.   HIST_ENTRY *return_value;
  446.  
  447.   if (which >= history_length || !history_length)
  448.     return_value = (HIST_ENTRY *)NULL;
  449.   else
  450.     {
  451.       register int i;
  452.       return_value = the_history[which];
  453.  
  454.       for (i = which; i < history_length; i++)
  455.     the_history[i] = the_history[i + 1];
  456.  
  457.       history_length--;
  458.     }
  459.  
  460.   return (return_value);
  461. }
  462.  
  463. /* Stifle the history list, remembering only MAX number of lines. */
  464. void
  465. stifle_history (max)
  466.      int max;
  467. {
  468.   if (max < 0)
  469.     max = 0;
  470.  
  471.   if (history_length > max)
  472.     {
  473.       register int i, j;
  474.  
  475.       /* This loses because we cannot free the data. */
  476.       for (i = 0; i < (history_length - max); i++)
  477.     {
  478.       free (the_history[i]->line);
  479.       free (the_history[i]);
  480.     }
  481.  
  482.       history_base = i;
  483.       for (j = 0, i = history_length - max; j < max; i++, j++)
  484.     the_history[j] = the_history[i];
  485.       the_history[j] = (HIST_ENTRY *)NULL;
  486.       history_length = j;
  487.     }
  488.  
  489.   history_stifled = 1;
  490.   max_input_history = max;
  491. }
  492.  
  493. /* Stop stifling the history.  This returns the previous amount the history
  494.  was stifled by.  The value is positive if the history was stifled, negative
  495.  if it wasn't. */
  496. int
  497. unstifle_history ()
  498. {
  499.   int result = max_input_history;
  500.  
  501.   if (history_stifled)
  502.     {
  503.       result = -result;
  504.       history_stifled = 0;
  505.     }
  506.  
  507.   return (result);
  508. }
  509.  
  510. int
  511. history_is_stifled ()
  512. {
  513.   return (history_stifled);
  514. }
  515.  
  516. /* Return the string that should be used in the place of this
  517.    filename.  This only matters when you don't specify the
  518.    filename to read_history (), or write_history (). */
  519. static char *
  520. history_filename (filename)
  521.      char *filename;
  522. {
  523.   char *return_val = filename ? savestring (filename) : (char *)NULL;
  524.  
  525.   if (!return_val)
  526.     {
  527.       char *home;
  528.       int home_len;
  529.  
  530.       home = getenv ("HOME");
  531.  
  532.       if (!home)
  533.     home = ".";
  534.  
  535.       home_len = strlen (home);
  536.       /* strlen(".history") == 8 */
  537.       return_val = xmalloc (2 + home_len + 8);
  538.  
  539.       strcpy (return_val, home);
  540.       return_val[home_len] = '/';
  541.       strcpy (return_val + home_len + 1, ".history");
  542.     }
  543.  
  544.   return (return_val);
  545. }
  546.  
  547. /* Add the contents of FILENAME to the history list, a line at a time.
  548.    If FILENAME is NULL, then read from ~/.history.  Returns 0 if
  549.    successful, or errno if not. */
  550. int
  551. read_history (filename)
  552.      char *filename;
  553. {
  554.   return (read_history_range (filename, 0, -1));
  555. }
  556.  
  557. /* Read a range of lines from FILENAME, adding them to the history list.
  558.    Start reading at the FROM'th line and end at the TO'th.  If FROM
  559.    is zero, start at the beginning.  If TO is less than FROM, read
  560.    until the end of the file.  If FILENAME is NULL, then read from
  561.    ~/.history.  Returns 0 if successful, or errno if not. */
  562. int
  563. read_history_range (filename, from, to)
  564.      char *filename;
  565.      int from, to;
  566. {
  567. #if defined (__EMX__)
  568. /*
  569. ** read_history_range works now with text files.
  570. ** Klaus Gebhardt, 1995
  571. */
  572.    register int line_start, line_end;
  573.    char *input, *buffer = (char *)NULL;
  574.    int file, current_line, st_size;
  575.    struct stat finfo;
  576.  
  577.    input = history_filename (filename);
  578.    file = open (input, O_RDONLY, 0666);
  579.    if ((file < 0) || (stat (input, &finfo) == -1))
  580.       error_and_exit:
  581.    {
  582.       if (file >= 0)  close (file);
  583.       if (input)      free (input);
  584.       if (buffer)     free (buffer);
  585.       return (errno);
  586.    }
  587.  
  588.    buffer = (char *)xmalloc (finfo.st_size + 1);
  589.    st_size=read (file, buffer, finfo.st_size);
  590.    close (file);
  591.  
  592.    if (to < 0)  to = st_size;
  593.  
  594.    line_start = line_end = current_line = 0;
  595.    while (line_start < st_size && current_line < from)
  596.    {
  597.       for (line_end = line_start; line_end < st_size; line_end++)
  598.      if (buffer[line_end] == '\n')
  599.      {
  600.         current_line++;
  601.         line_start = line_end + 1;
  602.         if (current_line == from)  break;
  603.      }
  604.    }
  605.  
  606.   for (line_end = line_start; line_end < st_size; line_end++)
  607.      if (buffer[line_end] == '\n')
  608.      {
  609.     buffer[line_end] = '\0';
  610.     if (buffer[line_start])  add_history (buffer + line_start);
  611.     current_line++;
  612.     if (current_line >= to)  break;
  613.     line_start = line_end + 1;
  614.      }
  615.  
  616.    if (input)   free (input);
  617.    if (buffer)  free (buffer);
  618.    return (0);
  619. #else
  620.   register int line_start, line_end;
  621.   char *input, *buffer = (char *)NULL;
  622.   int file, current_line;
  623.   struct stat finfo;
  624.  
  625.   input = history_filename (filename);
  626.   file = open (input, O_RDONLY, 0666);
  627.  
  628.   if ((file < 0) || (fstat (file, &finfo) == -1))
  629.     goto error_and_exit;
  630.  
  631.   buffer = xmalloc ((int)finfo.st_size + 1);
  632.  
  633.   if (read (file, buffer, finfo.st_size) != finfo.st_size)
  634.     {
  635.   error_and_exit:
  636.       if (file >= 0)
  637.     close (file);
  638.  
  639.       if (input)
  640.     free (input);
  641.  
  642.       if (buffer)
  643.     free (buffer);
  644.  
  645.       return (errno);
  646.     }
  647.  
  648.   close (file);
  649.  
  650.   /* Set TO to larger than end of file if negative. */
  651.   if (to < 0)
  652.     to = finfo.st_size;
  653.  
  654.   /* Start at beginning of file, work to end. */
  655.   line_start = line_end = current_line = 0;
  656.  
  657.   /* Skip lines until we are at FROM. */
  658.   while (line_start < finfo.st_size && current_line < from)
  659.     {
  660.       for (line_end = line_start; line_end < finfo.st_size; line_end++)
  661.     if (buffer[line_end] == '\n')
  662.       {
  663.         current_line++;
  664.         line_start = line_end + 1;
  665.         if (current_line == from)
  666.           break;
  667.       }
  668.     }
  669.  
  670.   /* If there are lines left to gobble, then gobble them now. */
  671.   for (line_end = line_start; line_end < finfo.st_size; line_end++)
  672.     if (buffer[line_end] == '\n')
  673.       {
  674.     buffer[line_end] = '\0';
  675.  
  676.     if (buffer[line_start])
  677.       add_history (buffer + line_start);
  678.  
  679.     current_line++;
  680.  
  681.     if (current_line >= to)
  682.       break;
  683.  
  684.     line_start = line_end + 1;
  685.       }
  686.  
  687.   if (input)
  688.     free (input);
  689.  
  690.   if (buffer)
  691.     free (buffer);
  692.  
  693.   return (0);
  694. #endif
  695. }
  696.  
  697. /* Truncate the history file FNAME, leaving only LINES trailing lines.
  698.    If FNAME is NULL, then use ~/.history. */
  699. int
  700. history_truncate_file (fname, lines)
  701.      char *fname;
  702.      register int lines;
  703. {
  704.   register int i;
  705.   int file, chars_read;
  706.   char *buffer = (char *)NULL, *filename;
  707.   struct stat finfo;
  708.  
  709.   filename = history_filename (fname);
  710.   file = open (filename, O_RDONLY, 0666);
  711.  
  712.   if (file == -1 || fstat (file, &finfo) == -1)
  713.     goto truncate_exit;
  714.  
  715.   buffer = xmalloc ((int)finfo.st_size + 1);
  716.   chars_read = read (file, buffer, finfo.st_size);
  717.   close (file);
  718.  
  719.   if (chars_read <= 0)
  720.     goto truncate_exit;
  721.  
  722.   /* Count backwards from the end of buffer until we have passed
  723.      LINES lines. */
  724.   for (i = chars_read - 1; lines && i; i--)
  725.     {
  726.       if (buffer[i] == '\n')
  727.     lines--;
  728.     }
  729.  
  730.   /* If this is the first line, then the file contains exactly the
  731.      number of lines we want to truncate to, so we don't need to do
  732.      anything.  It's the first line if we don't find a newline between
  733.      the current value of i and 0.  Otherwise, write from the start of
  734.      this line until the end of the buffer. */
  735.   for ( ; i; i--)
  736.     if (buffer[i] == '\n')
  737.       {
  738.     i++;
  739.     break;
  740.       }
  741.  
  742.   /* Write only if there are more lines in the file than we want to
  743.      truncate to. */
  744.   if (i && ((file = open (filename, O_WRONLY|O_TRUNC, 0666)) != -1))
  745.     {
  746.       write (file, buffer + i, finfo.st_size - i);
  747.       close (file);
  748.     }
  749.  
  750.  truncate_exit:
  751.   if (buffer)
  752.     free (buffer);
  753.  
  754.   free (filename);
  755.   return 0;
  756. }
  757.  
  758. #define HISTORY_APPEND 0
  759. #define HISTORY_OVERWRITE 1
  760.  
  761. /* Workhorse function for writing history.  Writes NELEMENT entries
  762.    from the history list to FILENAME.  OVERWRITE is non-zero if you
  763.    wish to replace FILENAME with the entries. */
  764. static int
  765. history_do_write (filename, nelements, overwrite)
  766.      char *filename;
  767.      int nelements, overwrite;
  768. {
  769.   register int i;
  770.   char *output = history_filename (filename);
  771.   int file, mode;
  772.  
  773.   mode = overwrite ? O_WRONLY | O_CREAT | O_TRUNC : O_WRONLY | O_APPEND;
  774.  
  775.   if ((file = open (output, mode, 0666)) == -1)
  776.     {
  777.       if (output)
  778.     free (output);
  779.  
  780.       return (errno);
  781.     }
  782.  
  783.   if (nelements > history_length)
  784.     nelements = history_length;
  785.  
  786.   /* Build a buffer of all the lines to write, and write them in one syscall.
  787.      Suggested by Peter Ho (peter@robosts.oxford.ac.uk). */
  788.   {
  789.     register int j = 0;
  790.     int buffer_size = 0;
  791.     char *buffer;
  792.  
  793.     /* Calculate the total number of bytes to write. */
  794.     for (i = history_length - nelements; i < history_length; i++)
  795.       buffer_size += 1 + strlen (the_history[i]->line);
  796.  
  797.     /* Allocate the buffer, and fill it. */
  798.     buffer = xmalloc (buffer_size);
  799.  
  800.     for (i = history_length - nelements; i < history_length; i++)
  801.       {
  802.     strcpy (buffer + j, the_history[i]->line);
  803.     j += strlen (the_history[i]->line);
  804.     buffer[j++] = '\n';
  805.       }
  806.  
  807.     write (file, buffer, buffer_size);
  808.     free (buffer);
  809.   }
  810.  
  811.   close (file);
  812.  
  813.   if (output)
  814.     free (output);
  815.  
  816.   return (0);
  817. }
  818.  
  819. /* Append NELEMENT entries to FILENAME.  The entries appended are from
  820.    the end of the list minus NELEMENTs up to the end of the list. */
  821. int
  822. append_history (nelements, filename)
  823.      int nelements;
  824.      char *filename;
  825. {
  826.   return (history_do_write (filename, nelements, HISTORY_APPEND));
  827. }
  828.  
  829. /* Overwrite FILENAME with the current history.  If FILENAME is NULL,
  830.    then write the history list to ~/.history.  Values returned
  831.    are as in read_history ().*/
  832. int
  833. write_history (filename)
  834.      char *filename;
  835. {
  836.   return (history_do_write (filename, history_length, HISTORY_OVERWRITE));
  837. }
  838.  
  839. /* Return the history entry at the current position, as determined by
  840.    history_offset.  If there is no entry there, return a NULL pointer. */
  841. HIST_ENTRY *
  842. current_history ()
  843. {
  844.   if ((history_offset == history_length) || !the_history)
  845.     return ((HIST_ENTRY *)NULL);
  846.   else
  847.     return (the_history[history_offset]);
  848. }
  849.  
  850. /* Back up history_offset to the previous history entry, and return
  851.    a pointer to that entry.  If there is no previous entry then return
  852.    a NULL pointer. */
  853. HIST_ENTRY *
  854. previous_history ()
  855. {
  856.   if (!history_offset)
  857.     return ((HIST_ENTRY *)NULL);
  858.   else
  859.     return (the_history[--history_offset]);
  860. }
  861.  
  862. /* Move history_offset forward to the next history entry, and return
  863.    a pointer to that entry.  If there is no next entry then return a
  864.    NULL pointer. */
  865. HIST_ENTRY *
  866. next_history ()
  867. {
  868.   if (history_offset == history_length)
  869.     return ((HIST_ENTRY *)NULL);
  870.   else
  871.     return (the_history[++history_offset]);
  872. }
  873.  
  874. /* Return the current history array.  The caller has to be carefull, since this
  875.    is the actual array of data, and could be bashed or made corrupt easily.
  876.    The array is terminated with a NULL pointer. */
  877. HIST_ENTRY **
  878. history_list ()
  879. {
  880.   return (the_history);
  881. }
  882.  
  883. /* Return the history entry which is logically at OFFSET in the history array.
  884.    OFFSET is relative to history_base. */
  885. HIST_ENTRY *
  886. history_get (offset)
  887.      int offset;
  888. {
  889.   int local_index = offset - history_base;
  890.  
  891.   if (local_index >= history_length ||
  892.       local_index < 0 ||
  893.       !the_history)
  894.     return ((HIST_ENTRY *)NULL);
  895.   return (the_history[local_index]);
  896. }
  897.  
  898. /* Search for STRING in the history list.  DIR is < 0 for searching
  899.    backwards.  POS is an absolute index into the history list at
  900.    which point to begin searching. */
  901. int
  902. history_search_pos (string, dir, pos)
  903.      char *string;
  904.      int dir, pos;
  905. {
  906.   int ret, old = where_history ();
  907.   history_set_pos (pos);
  908.   if (history_search (string, dir) == -1)
  909.     {
  910.       history_set_pos (old);
  911.       return (-1);
  912.     }
  913.   ret = where_history ();
  914.   history_set_pos (old);
  915.   return ret;
  916. }
  917.  
  918. /* Make the current history item be the one at POS, an absolute index.
  919.    Returns zero if POS is out of range, else non-zero. */
  920. int
  921. history_set_pos (pos)
  922.      int pos;
  923. {
  924.   if (pos > history_length || pos < 0 || !the_history)
  925.     return (0);
  926.   history_offset = pos;
  927.   return (1);
  928. }
  929.  
  930.  
  931. /* **************************************************************** */
  932. /*                                    */
  933. /*            History Expansion                */
  934. /*                                    */
  935. /* **************************************************************** */
  936.  
  937. /* Hairy history expansion on text, not tokens.  This is of general
  938.    use, and thus belongs in this library. */
  939.  
  940. /* The last string searched for in a !?string? search. */
  941. static char *search_string = (char *)NULL;
  942.  
  943. /* The last string matched by a !?string? search. */
  944. static char *search_match = (char *)NULL;
  945.  
  946. /* Return the event specified at TEXT + OFFSET modifying OFFSET to
  947.    point to after the event specifier.  Just a pointer to the history
  948.    line is returned; NULL is returned in the event of a bad specifier.
  949.    You pass STRING with *INDEX equal to the history_expansion_char that
  950.    begins this specification.
  951.    DELIMITING_QUOTE is a character that is allowed to end the string
  952.    specification for what to search for in addition to the normal
  953.    characters `:', ` ', `\t', `\n', and sometimes `?'.
  954.    So you might call this function like:
  955.    line = get_history_event ("!echo:p", &index, 0);  */
  956. char *
  957. get_history_event (string, caller_index, delimiting_quote)
  958.      char *string;
  959.      int *caller_index;
  960.      int delimiting_quote;
  961. {
  962.   register int i = *caller_index;
  963.   register char c;
  964.   HIST_ENTRY *entry;
  965.   int which, sign = 1;
  966.   int local_index, search_mode, substring_okay = 0;
  967.   char *temp;
  968.  
  969.   /* The event can be specified in a number of ways.
  970.  
  971.      !!   the previous command
  972.      !n   command line N
  973.      !-n  current command-line minus N
  974.      !str the most recent command starting with STR
  975.      !?str[?]
  976.       the most recent command containing STR
  977.  
  978.      All values N are determined via HISTORY_BASE. */
  979.  
  980.   if (string[i] != history_expansion_char)
  981.     return ((char *)NULL);
  982.  
  983.   /* Move on to the specification. */
  984.   i++;
  985.  
  986. #define RETURN_ENTRY(e, w) \
  987.     return ((e = history_get (w)) ? e->line : (char *)NULL)
  988.  
  989.   /* Handle !! case. */
  990.   if (string[i] == history_expansion_char)
  991.     {
  992.       i++;
  993.       which = history_base + (history_length - 1);
  994.       *caller_index = i;
  995.       RETURN_ENTRY (entry, which);
  996.     }
  997.  
  998.   /* Hack case of numeric line specification. */
  999.   if (string[i] == '-')
  1000.     {
  1001.       sign = -1;
  1002.       i++;
  1003.     }
  1004.  
  1005.   if (digit_p (string[i]))
  1006.     {
  1007.       /* Get the extent of the digits and compute the value. */
  1008.       for (which = 0; digit_p (string[i]); i++)
  1009.     which = (which * 10) + digit_value (string[i]);
  1010.  
  1011.       *caller_index = i;
  1012.  
  1013.       if (sign < 0)
  1014.     which = (history_length + history_base) - which;
  1015.  
  1016.       RETURN_ENTRY (entry, which);
  1017.     }
  1018.  
  1019.   /* This must be something to search for.  If the spec begins with
  1020.      a '?', then the string may be anywhere on the line.  Otherwise,
  1021.      the string must be found at the start of a line. */
  1022.   if (string[i] == '?')
  1023.     {
  1024.       substring_okay++;
  1025.       i++;
  1026.     }
  1027.  
  1028.   /* Only a closing `?' or a newline delimit a substring search string. */
  1029.   for (local_index = i; c = string[i]; i++)
  1030.     if ((!substring_okay && (whitespace (c) || c == ':' ||
  1031. #if defined (SHELL)
  1032.       member (c, ";&()|<>") ||
  1033. #endif /* SHELL */
  1034.       string[i] == delimiting_quote)) ||
  1035.     string[i] == '\n' ||
  1036.     (substring_okay && string[i] == '?'))
  1037.       break;
  1038.  
  1039.   temp = xmalloc (1 + (i - local_index));
  1040.   strncpy (temp, &string[local_index], (i - local_index));
  1041.   temp[i - local_index] = '\0';
  1042.  
  1043.   if (substring_okay && string[i] == '?')
  1044.     i++;
  1045.  
  1046.   *caller_index = i;
  1047.  
  1048. #define FAIL_SEARCH() \
  1049.   do { history_offset = history_length; free (temp) ; return (char *)NULL; } while (0)
  1050.  
  1051.   search_mode = substring_okay ? NON_ANCHORED_SEARCH : ANCHORED_SEARCH;
  1052.   while (1)
  1053.     {
  1054.       local_index = history_search_internal (temp, -1, search_mode);
  1055.  
  1056.       if (local_index < 0)
  1057.     FAIL_SEARCH ();
  1058.  
  1059.       if (local_index == 0 || substring_okay)
  1060.     {
  1061.       entry = current_history ();
  1062.       history_offset = history_length;
  1063.     
  1064.       /* If this was a substring search, then remember the
  1065.          string that we matched for word substitution. */
  1066.       if (substring_okay)
  1067.         {
  1068.           if (search_string)
  1069.         free (search_string);
  1070.           search_string = temp;
  1071.  
  1072.           if (search_match)
  1073.         free (search_match);
  1074.           search_match = history_find_word (entry->line, local_index);
  1075.         }
  1076.       else
  1077.         free (temp);
  1078.       return (entry->line);
  1079.     }
  1080.  
  1081.       if (history_offset)
  1082.     history_offset--;
  1083.       else
  1084.     FAIL_SEARCH ();
  1085.     }
  1086. #undef FAIL_SEARCH
  1087. #undef RETURN_ENTRY
  1088. }
  1089. #if defined (SHELL)
  1090. /* Function for extracting single-quoted strings.  Used for inhibiting
  1091.    history expansion within single quotes. */
  1092.  
  1093. /* Extract the contents of STRING as if it is enclosed in single quotes.
  1094.    SINDEX, when passed in, is the offset of the character immediately
  1095.    following the opening single quote; on exit, SINDEX is left pointing
  1096.    to the closing single quote. */
  1097. static void
  1098. rl_string_extract_single_quoted (string, sindex)
  1099.      char *string;
  1100.      int *sindex;
  1101. {
  1102.   register int i = *sindex;
  1103.  
  1104.   while (string[i] && string[i] != '\'')
  1105.     i++;
  1106.  
  1107.   *sindex = i;
  1108. }
  1109.  
  1110. static char *
  1111. quote_breaks (s)
  1112.      char *s;
  1113. {
  1114.   register char *p, *r;
  1115.   char *ret;
  1116.   int len = 3;
  1117.  
  1118.   for (p = s; p && *p; p++, len++)
  1119.     {
  1120.       if (*p == '\'')
  1121.     len += 3;
  1122.       else if (whitespace (*p) || *p == '\n')
  1123.     len += 2;
  1124.     }
  1125.  
  1126.   r = ret = xmalloc (len);
  1127.   *r++ = '\'';
  1128.   for (p = s; p && *p; )
  1129.     {
  1130.       if (*p == '\'')
  1131.     {
  1132.       *r++ = '\'';
  1133.       *r++ = '\\';
  1134.       *r++ = '\'';
  1135.       *r++ = '\'';
  1136.       p++;
  1137.     }
  1138.       else if (whitespace (*p) || *p == '\n')
  1139.     {
  1140.       *r++ = '\'';
  1141.       *r++ = *p++;
  1142.       *r++ = '\'';
  1143.     }
  1144.       else
  1145.     *r++ = *p++;
  1146.     }
  1147.   *r++ = '\'';
  1148.   *r = '\0';
  1149.   return ret;
  1150. }
  1151. #endif /* SHELL */
  1152.  
  1153. static char *
  1154. hist_error(s, start, current, errtype)
  1155.       char *s;
  1156.       int start, current, errtype;
  1157. {
  1158.   char *temp, *emsg;
  1159.   int ll, elen;
  1160.  
  1161.   ll = current - start;
  1162.  
  1163.   switch (errtype)
  1164.     {
  1165.     case EVENT_NOT_FOUND:
  1166.       emsg = "event not found";
  1167.       elen = 15;
  1168.       break;
  1169.     case BAD_WORD_SPEC:
  1170.       emsg = "bad word specifier";
  1171.       elen = 18;
  1172.       break;
  1173.     case SUBST_FAILED:
  1174.       emsg = "substitution failed";
  1175.       elen = 19;
  1176.       break;
  1177.     case BAD_MODIFIER:
  1178.       emsg = "unrecognized history modifier";
  1179.       elen = 29;
  1180.       break;
  1181.     default:
  1182.       emsg = "unknown expansion error";
  1183.       elen = 23;
  1184.       break;
  1185.     }
  1186.  
  1187.   temp = xmalloc (ll + elen + 3);
  1188.   strncpy (temp, s + start, ll);
  1189.   temp[ll] = ':';
  1190.   temp[ll + 1] = ' ';
  1191.   strcpy (temp + ll + 2, emsg);
  1192.   return (temp);
  1193. }
  1194.  
  1195. /* Get a history substitution string from STR starting at *IPTR
  1196.    and return it.  The length is returned in LENPTR.
  1197.  
  1198.    A backslash can quote the delimiter.  If the string is the
  1199.    empty string, the previous pattern is used.  If there is
  1200.    no previous pattern for the lhs, the last history search
  1201.    string is used.
  1202.  
  1203.    If IS_RHS is 1, we ignore empty strings and set the pattern
  1204.    to "" anyway.  subst_lhs is not changed if the lhs is empty;
  1205.    subst_rhs is allowed to be set to the empty string. */
  1206.  
  1207. static char *
  1208. get_subst_pattern (str, iptr, delimiter, is_rhs, lenptr)
  1209.      char *str;
  1210.      int *iptr, delimiter, is_rhs, *lenptr;
  1211. {
  1212.   register int si, i, j, k;
  1213.   char *s = (char *) NULL;
  1214.  
  1215.   i = *iptr;
  1216.  
  1217.   for (si = i; str[si] && str[si] != delimiter; si++)
  1218.     if (str[si] == '\\' && str[si + 1] == delimiter)
  1219.       si++;
  1220.  
  1221.   if (si > i || is_rhs)
  1222.     {
  1223.       s = xmalloc (si - i + 1);
  1224.       for (j = 0, k = i; k < si; j++, k++)
  1225.     {
  1226.       /* Remove a backslash quoting the search string delimiter. */
  1227.       if (str[k] == '\\' && str[k + 1] == delimiter)
  1228.         k++;
  1229.       s[j] = str[k];
  1230.     }
  1231.       s[j] = '\0';
  1232.       if (lenptr)
  1233.         *lenptr = j;
  1234.     }
  1235.  
  1236.   i = si;
  1237.   if (str[i])
  1238.     i++;
  1239.   *iptr = i;
  1240.  
  1241.   return s;
  1242. }
  1243.  
  1244. static void
  1245. postproc_subst_rhs ()
  1246. {
  1247.   char *new;
  1248.   int i, j, new_size;
  1249.  
  1250.   new = xmalloc (new_size = subst_rhs_len + subst_lhs_len);
  1251.   for (i = j = 0; i < subst_rhs_len; i++)
  1252.     {
  1253.       if (subst_rhs[i] == '&')
  1254.     {
  1255.       if (j + subst_lhs_len >= new_size)
  1256.         new = xrealloc (new, (new_size = new_size * 2 + subst_lhs_len));
  1257.       strcpy (new + j, subst_lhs);
  1258.       j += subst_lhs_len;
  1259.     }
  1260.       else
  1261.     {
  1262.       /* a single backslash protects the `&' from lhs interpolation */
  1263.       if (subst_rhs[i] == '\\' && subst_rhs[i + 1] == '&')
  1264.         i++;
  1265.       if (j >= new_size)
  1266.         new = xrealloc (new, new_size *= 2);
  1267.       new[j++] = subst_rhs[i];
  1268.     }
  1269.     }
  1270.   new[j] = '\0';
  1271.   free (subst_rhs);
  1272.   subst_rhs = new;
  1273.   subst_rhs_len = j;
  1274. }
  1275.  
  1276. /* Expand the bulk of a history specifier starting at STRING[START].
  1277.    Returns 0 if everything is OK, -1 if an error occurred, and 1
  1278.    if the `p' modifier was supplied and the caller should just print
  1279.    the returned string.  Returns the new index into string in
  1280.    *END_INDEX_PTR, and the expanded specifier in *RET_STRING. */
  1281. static int
  1282. history_expand_internal (string, start, end_index_ptr, ret_string, current_line)
  1283.      char *string;
  1284.      int start, *end_index_ptr;
  1285.      char **ret_string;
  1286.      char *current_line;    /* for !# */
  1287. {
  1288.   int i, n, starting_index;
  1289.   int substitute_globally, want_quotes, print_only;
  1290.   char *event, *temp, *result, *tstr, *t, c, *word_spec;
  1291.   int result_len;
  1292.  
  1293.   result = xmalloc (result_len = 128);
  1294.  
  1295.   i = start;
  1296.  
  1297.   /* If it is followed by something that starts a word specifier,
  1298.      then !! is implied as the event specifier. */
  1299.  
  1300.   if (member (string[i + 1], ":$*%^"))
  1301.     {
  1302.       char fake_s[3];
  1303.       int fake_i = 0;
  1304.       i++;
  1305.       fake_s[0] = fake_s[1] = history_expansion_char;
  1306.       fake_s[2] = '\0';
  1307.       event = get_history_event (fake_s, &fake_i, 0);
  1308.     }
  1309.   else if (string[i + 1] == '#')
  1310.     {
  1311.       i += 2;
  1312.       event = current_line;
  1313.     }
  1314.   else
  1315.     {
  1316.       int quoted_search_delimiter = 0;
  1317.  
  1318.       /* If the character before this `!' is a double or single
  1319.      quote, then this expansion takes place inside of the
  1320.      quoted string.  If we have to search for some text ("!foo"),
  1321.      allow the delimiter to end the search string. */
  1322.       if (i && (string[i - 1] == '\'' || string[i - 1] == '"'))
  1323.     quoted_search_delimiter = string[i - 1];
  1324.       event = get_history_event (string, &i, quoted_search_delimiter);
  1325.     }
  1326.       
  1327.   if (!event)
  1328.     {
  1329.       *ret_string = hist_error (string, start, i, EVENT_NOT_FOUND);
  1330.       free (result);
  1331.       return (-1);
  1332.     }
  1333.  
  1334.   /* If a word specifier is found, then do what that requires. */
  1335.   starting_index = i;
  1336.   word_spec = get_history_word_specifier (string, event, &i);
  1337.  
  1338.   /* There is no such thing as a `malformed word specifier'.  However,
  1339.      it is possible for a specifier that has no match.  In that case,
  1340.      we complain. */
  1341.   if (word_spec == (char *)&error_pointer)
  1342.     {
  1343.       *ret_string = hist_error (string, starting_index, i, BAD_WORD_SPEC);
  1344.       free (result);
  1345.       return (-1);
  1346.     }
  1347.  
  1348.   /* If no word specifier, than the thing of interest was the event. */
  1349.   if (!word_spec)
  1350.     temp = savestring (event);
  1351.   else
  1352.     {
  1353.       temp = savestring (word_spec);
  1354.       free (word_spec);
  1355.     }
  1356.  
  1357.   /* Perhaps there are other modifiers involved.  Do what they say. */
  1358.   want_quotes = substitute_globally = print_only = 0;
  1359.   starting_index = i;
  1360.  
  1361.   while (string[i] == ':')
  1362.     {
  1363.       c = string[i + 1];
  1364.  
  1365.       if (c == 'g')
  1366.     {
  1367.       substitute_globally = 1;
  1368.       i++;
  1369.       c = string[i + 1];
  1370.     }
  1371.  
  1372.       switch (c)
  1373.     {
  1374.     default:
  1375.       *ret_string = hist_error (string, i+1, i+2, BAD_MODIFIER);
  1376.       free (result);
  1377.       free (temp);
  1378.       return -1;
  1379.  
  1380. #if defined (SHELL)
  1381.     case 'q':
  1382.       want_quotes = 'q';
  1383.       break;
  1384.  
  1385.     case 'x':
  1386.       want_quotes = 'x';
  1387.       break;
  1388. #endif /* SHELL */
  1389.  
  1390.       /* :p means make this the last executed line.  So we
  1391.          return an error state after adding this line to the
  1392.          history. */
  1393.     case 'p':
  1394.       print_only++;
  1395.       break;
  1396.  
  1397.       /* :t discards all but the last part of the pathname. */
  1398.     case 't':
  1399.       tstr = strrchr (temp, '/');
  1400.       if (tstr)
  1401.         {
  1402.           tstr++;
  1403.           t = savestring (tstr);
  1404.           free (temp);
  1405.           temp = t;
  1406.         }
  1407.       break;
  1408.  
  1409.       /* :h discards the last part of a pathname. */
  1410.     case 'h':
  1411.       tstr = strrchr (temp, '/');
  1412.       if (tstr)
  1413.         *tstr = '\0';
  1414.       break;
  1415.  
  1416.       /* :r discards the suffix. */
  1417.     case 'r':
  1418.       tstr = strrchr (temp, '.');
  1419.       if (tstr)
  1420.         *tstr = '\0';
  1421.       break;
  1422.  
  1423.       /* :e discards everything but the suffix. */
  1424.     case 'e':
  1425.       tstr = strrchr (temp, '.');
  1426.       if (tstr)
  1427.         {
  1428.           t = savestring (tstr);
  1429.           free (temp);
  1430.           temp = t;
  1431.         }
  1432.       break;
  1433.  
  1434.     /* :s/this/that substitutes `that' for the first
  1435.        occurrence of `this'.  :gs/this/that substitutes `that'
  1436.        for each occurrence of `this'.  :& repeats the last
  1437.        substitution.  :g& repeats the last substitution
  1438.        globally. */
  1439.  
  1440.     case '&':
  1441.     case 's':
  1442.       {
  1443.         char *new_event, *t;
  1444.         int delimiter, failed, si, l_temp;
  1445.  
  1446.         if (c == 's')
  1447.           {
  1448.         if (i + 2 < (int)strlen (string))
  1449.           delimiter = string[i + 2];
  1450.         else
  1451.           break;    /* no search delimiter */
  1452.  
  1453.         i += 3;
  1454.  
  1455.         t = get_subst_pattern (string, &i, delimiter, 0, &subst_lhs_len);
  1456.         /* An empty substitution lhs with no previous substitution
  1457.            uses the last search string as the lhs. */
  1458.         if (t)
  1459.           {
  1460.             if (subst_lhs)
  1461.               free (subst_lhs);
  1462.             subst_lhs = t;
  1463.           }
  1464.         else if (!subst_lhs)
  1465.           {
  1466.             if (search_string && *search_string)
  1467.               {
  1468.             subst_lhs = savestring (search_string);
  1469.             subst_lhs_len = strlen (subst_lhs);
  1470.               }
  1471.             else
  1472.               {
  1473.                 subst_lhs = (char *) NULL;
  1474.                 subst_lhs_len = 0;
  1475.               }
  1476.           }
  1477.  
  1478.         /* If there is no lhs, the substitution can't succeed. */
  1479.         if (subst_lhs_len == 0)
  1480.           {
  1481.             *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1482.             free (result);
  1483.             free (temp);
  1484.             return -1;
  1485.           }
  1486.  
  1487.         if (subst_rhs)
  1488.           free (subst_rhs);
  1489.         subst_rhs = get_subst_pattern (string, &i, delimiter, 1, &subst_rhs_len);
  1490.  
  1491.         /* If `&' appears in the rhs, it's supposed to be replaced
  1492.            with the lhs. */
  1493.         if (member ('&', subst_rhs))
  1494.           postproc_subst_rhs ();
  1495.           }
  1496.         else
  1497.           i += 2;
  1498.  
  1499.         l_temp = strlen (temp);
  1500.         /* Ignore impossible cases. */
  1501.         if (subst_lhs_len > l_temp)
  1502.           {
  1503.         *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1504.         free (result);
  1505.         free (temp);
  1506.         return (-1);
  1507.           }
  1508.  
  1509.         /* Find the first occurrence of THIS in TEMP. */
  1510.         si = 0;
  1511.         for (failed = 1; (si + subst_lhs_len) <= l_temp; si++)
  1512.           if (STREQN (temp+si, subst_lhs, subst_lhs_len))
  1513.         {
  1514.           int len = subst_rhs_len - subst_lhs_len + l_temp;
  1515.           new_event = xmalloc (1 + len);
  1516.           strncpy (new_event, temp, si);
  1517.           strncpy (new_event + si, subst_rhs, subst_rhs_len);
  1518.           strncpy (new_event + si + subst_rhs_len,
  1519.                temp + si + subst_lhs_len,
  1520.                l_temp - (si + subst_lhs_len));
  1521.           new_event[len] = '\0';
  1522.           free (temp);
  1523.           temp = new_event;
  1524.  
  1525.           failed = 0;
  1526.  
  1527.           if (substitute_globally)
  1528.             {
  1529.               si += subst_rhs_len;
  1530.               l_temp = strlen (temp);
  1531.               substitute_globally++;
  1532.               continue;
  1533.             }
  1534.           else
  1535.             break;
  1536.         }
  1537.  
  1538.         if (substitute_globally > 1)
  1539.           {
  1540.         substitute_globally = 0;
  1541.         continue;    /* don't want to increment i */
  1542.           }
  1543.  
  1544.         if (failed == 0)
  1545.           continue;        /* don't want to increment i */
  1546.  
  1547.         *ret_string = hist_error (string, starting_index, i, SUBST_FAILED);
  1548.         free (result);
  1549.         free (temp);
  1550.         return (-1);
  1551.       }
  1552.     }
  1553.       i += 2;
  1554.     }
  1555.   /* Done with modfiers. */
  1556.   /* Believe it or not, we have to back the pointer up by one. */
  1557.   --i;
  1558.  
  1559. #if defined (SHELL)
  1560.   if (want_quotes)
  1561.     {
  1562.       char *x;
  1563.  
  1564.       if (want_quotes == 'q')
  1565.     x = single_quote (temp);
  1566.       else if (want_quotes == 'x')
  1567.     x = quote_breaks (temp);
  1568.       else
  1569.     x = savestring (temp);
  1570.  
  1571.       free (temp);
  1572.       temp = x;
  1573.     }
  1574. #endif /* SHELL */
  1575.  
  1576.   n = strlen (temp);
  1577.   if (n > result_len)
  1578.     result = xrealloc (result, n + 2);
  1579.   strcpy (result, temp);
  1580.   free (temp);
  1581.  
  1582.   *end_index_ptr = i;
  1583.   *ret_string = result;
  1584.   return (print_only);
  1585. }
  1586.  
  1587. /* Expand the string STRING, placing the result into OUTPUT, a pointer
  1588.    to a string.  Returns:
  1589.  
  1590.   -1) If there was an error in expansion.
  1591.    0) If no expansions took place (or, if the only change in
  1592.       the text was the de-slashifying of the history expansion
  1593.       character)
  1594.    1) If expansions did take place
  1595.    2) If the `p' modifier was given and the caller should print the result
  1596.  
  1597.   If an error ocurred in expansion, then OUTPUT contains a descriptive
  1598.   error message. */
  1599.  
  1600. #define ADD_STRING(s) \
  1601.     do \
  1602.       { \
  1603.         int sl = strlen (s); \
  1604.         j += sl; \
  1605.         if (j >= result_len) \
  1606.           { \
  1607.         while (j >= result_len) \
  1608.           result_len += 128; \
  1609.         result = xrealloc (result, result_len); \
  1610.           } \
  1611.         strcpy (result + j - sl, s); \
  1612.       } \
  1613.     while (0)
  1614.  
  1615. #define ADD_CHAR(c) \
  1616.     do \
  1617.       { \
  1618.         if (j >= result_len - 1) \
  1619.           result = xrealloc (result, result_len += 64); \
  1620.         result[j++] = c; \
  1621.         result[j] = '\0'; \
  1622.       } \
  1623.     while (0)
  1624.  
  1625. int
  1626. history_expand (hstring, output)
  1627.      char *hstring;
  1628.      char **output;
  1629. {
  1630.   register int j;
  1631.   int i, r, l, passc, cc, modified, eindex, only_printing;
  1632.   char *string;
  1633.  
  1634.   /* The output string, and its length. */
  1635.   int result_len;
  1636.   char *result;
  1637.  
  1638.   /* Used when adding the string. */
  1639.   char *temp;
  1640.  
  1641.   /* Setting the history expansion character to 0 inhibits all
  1642.      history expansion. */
  1643.   if (history_expansion_char == 0)
  1644.     {
  1645.       *output = savestring (hstring);
  1646.       return (0);
  1647.     }
  1648.     
  1649.   /* Prepare the buffer for printing error messages. */
  1650.   result = xmalloc (result_len = 256);
  1651.   result[0] = '\0';
  1652.  
  1653.   only_printing = modified = 0;
  1654.   l = strlen (hstring);
  1655.  
  1656.   /* Grovel the string.  Only backslash can quote the history escape
  1657.      character.  We also handle arg specifiers. */
  1658.  
  1659.   /* Before we grovel forever, see if the history_expansion_char appears
  1660.      anywhere within the text. */
  1661.  
  1662.   /* The quick substitution character is a history expansion all right.  That
  1663.      is to say, "^this^that^" is equivalent to "!!:s^this^that^", and in fact,
  1664.      that is the substitution that we do. */
  1665.   if (hstring[0] == history_subst_char)
  1666.     {
  1667.       string = xmalloc (l + 5);
  1668.  
  1669.       string[0] = string[1] = history_expansion_char;
  1670.       string[2] = ':';
  1671.       string[3] = 's';
  1672.       strcpy (string + 4, hstring);
  1673.       l += 4;
  1674.     }
  1675.   else
  1676.     {
  1677.       string = hstring;
  1678.       /* If not quick substitution, still maybe have to do expansion. */
  1679.  
  1680.       /* `!' followed by one of the characters in history_no_expand_chars
  1681.      is NOT an expansion. */
  1682.       for (i = 0; string[i]; i++)
  1683.     {
  1684.       cc = string[i + 1];
  1685.           if (string[i] == history_expansion_char)
  1686.         {
  1687.           if (!cc || member (cc, history_no_expand_chars))
  1688.         continue;
  1689. #if defined (SHELL)
  1690.           /* The shell uses ! as a pattern negation character
  1691.              in globbing [...] expressions, so let those pass
  1692.              without expansion. */
  1693.           else if (i > 0 && (string[i - 1] == '[') &&
  1694.                member (']', string + i + 1))
  1695.         continue;
  1696. #endif /* SHELL */
  1697.           else
  1698.         break;
  1699.         }
  1700. #if defined (SHELL)
  1701.       else if (string[i] == '\'')
  1702.         {
  1703.           /* If this is bash, single quotes inhibit history expansion. */
  1704.           i++;
  1705.           rl_string_extract_single_quoted (string, &i);
  1706.         }
  1707.       else if (string[i] == '\\')
  1708.         {
  1709.           /* If this is bash, allow backslashes to quote single
  1710.          quotes and
  1711.          the history expansion character. */
  1712.           if (cc == '\'' || cc == history_expansion_char)
  1713.         i++;
  1714.         }
  1715. #endif /* SHELL */
  1716.     }
  1717.       
  1718.       if (string[i] != history_expansion_char)
  1719.     {
  1720.       free (result);
  1721.       *output = savestring (string);
  1722.       return (0);
  1723.     }
  1724.     }
  1725.  
  1726.   /* Extract and perform the substitution. */
  1727.   for (passc = i = j = 0; i < l; i++)
  1728.     {
  1729.       int tchar = string[i];
  1730.  
  1731.       if (passc)
  1732.     {
  1733.       passc = 0;
  1734.       ADD_CHAR (tchar);
  1735.       continue;
  1736.     }
  1737.  
  1738.       if (tchar == history_expansion_char)
  1739.     tchar = -3;
  1740.  
  1741.       switch (tchar)
  1742.     {
  1743.     default:
  1744.       ADD_CHAR (string[i]);
  1745.       break;
  1746.  
  1747.     case '\\':
  1748.       passc++;
  1749.       ADD_CHAR (tchar);
  1750.       break;
  1751.  
  1752. #if defined (SHELL)
  1753.     case '\'':
  1754.       {
  1755.         /* If this is bash, single quotes inhibit history expansion. */
  1756.         int quote, slen;
  1757.  
  1758.         quote = i++;
  1759.         rl_string_extract_single_quoted (string, &i);
  1760.  
  1761.         slen = i - quote + 2;
  1762.         temp = xmalloc (slen);
  1763.         strncpy (temp, string + quote, slen);
  1764.         temp[slen - 1] = '\0';
  1765.         ADD_STRING (temp);
  1766.         free (temp);
  1767.         break;
  1768.       }
  1769. #endif /* SHELL */
  1770.  
  1771.     case -3:        /* history_expansion_char */
  1772.       cc = string[i + 1];
  1773.  
  1774.       /* If the history_expansion_char is followed by one of the
  1775.          characters in history_no_expand_chars, then it is not a
  1776.          candidate for expansion of any kind. */
  1777.       if (member (cc, history_no_expand_chars))
  1778.         {
  1779.           ADD_CHAR (string[i]);
  1780.           break;
  1781.         }
  1782.  
  1783. #if defined (NO_BANG_HASH_MODIFIERS)
  1784.       /* There is something that is listed as a `word specifier' in csh
  1785.          documentation which means `the expanded text to this point'.
  1786.          That is not a word specifier, it is an event specifier.  If we
  1787.          don't want to allow modifiers with `!#', just stick the current
  1788.          output line in again. */
  1789.       if (cc == '#')
  1790.         {
  1791.           if (result)
  1792.         {
  1793.           temp = xmalloc (1 + strlen (result));
  1794.           strcpy (temp, result);
  1795.           ADD_STRING (temp);
  1796.           free (temp);
  1797.         }
  1798.           i++;
  1799.           break;
  1800.         }
  1801. #endif
  1802.  
  1803.       r = history_expand_internal (string, i, &eindex, &temp, result);
  1804.       if (r < 0)
  1805.         {
  1806.           *output = temp;
  1807.           free (result);
  1808.           if (string != hstring)
  1809.         free (string);
  1810.           return -1;
  1811.         }
  1812.       else
  1813.         {
  1814.           if (temp)
  1815.         {
  1816.           modified++;
  1817.           if (*temp)
  1818.             ADD_STRING (temp);
  1819.           free (temp);
  1820.         }
  1821.           only_printing = r == 1;
  1822.           i = eindex;
  1823.         }
  1824.       break;
  1825.     }
  1826.     }
  1827.  
  1828.   *output = result;
  1829.   if (string != hstring)
  1830.     free (string);
  1831.  
  1832.   if (only_printing)
  1833.     {
  1834.       add_history (result);
  1835.       return (2);
  1836.     }
  1837.  
  1838.   return (modified != 0);
  1839. }
  1840.  
  1841. /* Return a consed string which is the word specified in SPEC, and found
  1842.    in FROM.  NULL is returned if there is no spec.  The address of
  1843.    ERROR_POINTER is returned if the word specified cannot be found.
  1844.    CALLER_INDEX is the offset in SPEC to start looking; it is updated
  1845.    to point to just after the last character parsed. */
  1846. static char *
  1847. get_history_word_specifier (spec, from, caller_index)
  1848.      char *spec, *from;
  1849.      int *caller_index;
  1850. {
  1851.   register int i = *caller_index;
  1852.   int first, last;
  1853.   int expecting_word_spec = 0;
  1854.   char *result;
  1855.  
  1856.   /* The range of words to return doesn't exist yet. */
  1857.   first = last = 0;
  1858.   result = (char *)NULL;
  1859.  
  1860.   /* If we found a colon, then this *must* be a word specification.  If
  1861.      it isn't, then it is an error. */
  1862.   if (spec[i] == ':')
  1863.     {
  1864.       i++;
  1865.       expecting_word_spec++;
  1866.     }
  1867.  
  1868.   /* Handle special cases first. */
  1869.  
  1870.   /* `%' is the word last searched for. */
  1871.   if (spec[i] == '%')
  1872.     {
  1873.       *caller_index = i + 1;
  1874.       return (search_match ? savestring (search_match) : savestring (""));
  1875.     }
  1876.  
  1877.   /* `*' matches all of the arguments, but not the command. */
  1878.   if (spec[i] == '*')
  1879.     {
  1880.       *caller_index = i + 1;
  1881.       result = history_arg_extract (1, '$', from);
  1882.       return (result ? result : savestring (""));
  1883.     }
  1884.  
  1885.   /* `$' is last arg. */
  1886.   if (spec[i] == '$')
  1887.     {
  1888.       *caller_index = i + 1;
  1889.       return (history_arg_extract ('$', '$', from));
  1890.     }
  1891.  
  1892.   /* Try to get FIRST and LAST figured out. */
  1893.  
  1894.   if (spec[i] == '-')
  1895.     first = 0;
  1896.   else if (spec[i] == '^')
  1897.     first = 1;
  1898.   else if (digit_p (spec[i]) && expecting_word_spec)
  1899.     {
  1900.       for (first = 0; digit_p (spec[i]); i++)
  1901.     first = (first * 10) + digit_value (spec[i]);
  1902.     }
  1903.   else
  1904.     return ((char *)NULL);    /* no valid `first' for word specifier */
  1905.  
  1906.   if (spec[i] == '^' || spec[i] == '*')
  1907.     {
  1908.       last = (spec[i] == '^') ? 1 : '$';    /* x* abbreviates x-$ */
  1909.       i++;
  1910.     }
  1911.   else if (spec[i] != '-')
  1912.     last = first;
  1913.   else
  1914.     {
  1915.       i++;
  1916.  
  1917.       if (digit_p (spec[i]))
  1918.     {
  1919.       for (last = 0; digit_p (spec[i]); i++)
  1920.         last = (last * 10) + digit_value (spec[i]);
  1921.     }
  1922.       else if (spec[i] == '$')
  1923.     {
  1924.       i++;
  1925.       last = '$';
  1926.     }
  1927.       else if (!spec[i] || spec[i] == ':')  /* could be modifier separator */
  1928.     last = -1;        /* x- abbreviates x-$ omitting word `$' */
  1929.     }
  1930.  
  1931.   *caller_index = i;
  1932.  
  1933.   if (last >= first || last == '$' || last < 0)
  1934.     result = history_arg_extract (first, last, from);
  1935.  
  1936.   return (result ? result : (char *)&error_pointer);
  1937. }
  1938.  
  1939. /* Extract the args specified, starting at FIRST, and ending at LAST.
  1940.    The args are taken from STRING.  If either FIRST or LAST is < 0,
  1941.    then make that arg count from the right (subtract from the number of
  1942.    tokens, so that FIRST = -1 means the next to last token on the line).
  1943.    If LAST is `$' the last arg from STRING is used. */
  1944. char *
  1945. history_arg_extract (first, last, string)
  1946.      int first, last;
  1947.      char *string;
  1948. {
  1949.   register int i, len;
  1950.   char *result = (char *)NULL;
  1951.   int size = 0, offset = 0;
  1952.   char **list;
  1953.  
  1954.   /* XXX - think about making history_tokenize return a struct array,
  1955.      each struct in array being a string and a length to avoid the
  1956.      calls to strlen below. */
  1957.   if ((list = history_tokenize (string)) == NULL)
  1958.     return ((char *)NULL);
  1959.  
  1960.   for (len = 0; list[len]; len++)
  1961.     ;
  1962.  
  1963.   if (last < 0)
  1964.     last = len + last - 1;
  1965.  
  1966.   if (first < 0)
  1967.     first = len + first - 1;
  1968.  
  1969.   if (last == '$')
  1970.     last = len - 1;
  1971.  
  1972.   if (first == '$')
  1973.     first = len - 1;
  1974.  
  1975.   last++;
  1976.  
  1977.   if (first >= len || last > len || first < 0 || last < 0 || first > last)
  1978.     result = ((char *)NULL);
  1979.   else
  1980.     {
  1981.       for (size = 0, i = first; i < last; i++)
  1982.     size += strlen (list[i]) + 1;
  1983.       result = xmalloc (size + 1);
  1984.       result[0] = '\0';
  1985.  
  1986.       for (i = first; i < last; i++)
  1987.     {
  1988.       strcpy (result + offset, list[i]);
  1989.       offset += strlen (list[i]);
  1990.       if (i + 1 < last)
  1991.         {
  1992.                 result[offset++] = ' ';
  1993.           result[offset] = 0;
  1994.         }
  1995.     }
  1996.     }
  1997.  
  1998.   for (i = 0; i < len; i++)
  1999.     free (list[i]);
  2000.   free (list);
  2001.  
  2002.   return (result);
  2003. }
  2004.  
  2005. #define slashify_in_quotes "\\`\"$"
  2006.  
  2007. /* Parse STRING into tokens and return an array of strings.  If WIND is
  2008.    not -1 and INDP is not null, we also want the word surrounding index
  2009.    WIND.  The position in the returned array of strings is returned in
  2010.    *INDP. */
  2011. static char **
  2012. history_tokenize_internal (string, wind, indp)
  2013.      char *string;
  2014.      int wind, *indp;
  2015. {
  2016.   char **result = (char **)NULL;
  2017.   register int i, start, result_index, size;
  2018.   int len;
  2019.  
  2020.   i = result_index = size = 0;
  2021.  
  2022.   /* Get a token, and stuff it into RESULT.  The tokens are split
  2023.      exactly where the shell would split them. */
  2024.   while (string[i])
  2025.     {
  2026.       int delimiter = 0;
  2027.  
  2028.       /* Skip leading whitespace. */
  2029.       for (; string[i] && whitespace (string[i]); i++)
  2030.     ;
  2031.       if (!string[i] || string[i] == history_comment_char)
  2032.     return (result);
  2033.  
  2034.       start = i;
  2035.       
  2036.       if (member (string[i], "()\n"))
  2037.     {
  2038.       i++;
  2039.       goto got_token;
  2040.     }
  2041.  
  2042.       if (member (string[i], "<>;&|$"))
  2043.     {
  2044.       int peek = string[i + 1];
  2045.  
  2046.       if (peek == string[i] && peek != '$')
  2047.         {
  2048.           if (peek == '<' && string[i + 2] == '-')
  2049.         i++;
  2050.           i += 2;
  2051.           goto got_token;
  2052.         }
  2053.       else
  2054.         {
  2055.           if ((peek == '&' && (string[i] == '>' || string[i] == '<')) ||
  2056.           ((peek == '>') && (string[i] == '&')) ||
  2057.           ((peek == '(') && (string[i] == '$')))
  2058.         {
  2059.           i += 2;
  2060.           goto got_token;
  2061.         }
  2062.         }
  2063.       if (string[i] != '$')
  2064.         {
  2065.           i++;
  2066.           goto got_token;
  2067.         }
  2068.     }
  2069.  
  2070.       /* Get word from string + i; */
  2071.  
  2072.       if (member (string[i], "\"'`"))
  2073.     delimiter = string[i++];
  2074.  
  2075.       for (; string[i]; i++)
  2076.     {
  2077.       if (string[i] == '\\' && string[i + 1] == '\n')
  2078.         {
  2079.           i++;
  2080.           continue;
  2081.         }
  2082.  
  2083.       if (string[i] == '\\' && delimiter != '\'' &&
  2084.           (delimiter != '"' || member (string[i], slashify_in_quotes)))
  2085.         {
  2086.           i++;
  2087.           continue;
  2088.         }
  2089.  
  2090.       if (delimiter && string[i] == delimiter)
  2091.         {
  2092.           delimiter = 0;
  2093.           continue;
  2094.         }
  2095.  
  2096.       if (!delimiter && (member (string[i], " \t\n;&()|<>")))
  2097.         break;
  2098.  
  2099.       if (!delimiter && member (string[i], "\"'`"))
  2100.         delimiter = string[i];
  2101.     }
  2102.     got_token:
  2103.  
  2104.       /* If we are looking for the word in which the character at a
  2105.      particular index falls, remember it. */
  2106.       if (indp && wind >= 0 && wind >= start && wind < i)
  2107.         *indp = result_index;
  2108.  
  2109.       len = i - start;
  2110.       if (result_index + 2 >= size)
  2111.     result = (char **)xrealloc (result, ((size += 10) * sizeof (char *)));
  2112.       result[result_index] = xmalloc (1 + len);
  2113.       strncpy (result[result_index], string + start, len);
  2114.       result[result_index][len] = '\0';
  2115.       result[++result_index] = (char *)NULL;
  2116.     }
  2117.  
  2118.   return (result);
  2119. }
  2120.  
  2121. /* Return an array of tokens, much as the shell might.  The tokens are
  2122.    parsed out of STRING. */
  2123. char **
  2124. history_tokenize (string)
  2125.      char *string;
  2126. {
  2127.   return (history_tokenize_internal (string, -1, (int *)NULL));
  2128. }
  2129.  
  2130. /* Find and return the word which contains the character at index IND
  2131.    in the history line LINE.  Used to save the word matched by the
  2132.    last history !?string? search. */
  2133. static char *
  2134. history_find_word (line, ind)
  2135.      char *line;
  2136.      int ind;
  2137. {
  2138.   char **words, *s;
  2139.   int i, wind;
  2140.  
  2141.   words = history_tokenize_internal (line, ind, &wind);
  2142.   if (wind == -1)
  2143.     return ((char *)NULL);
  2144.   s = words[wind];
  2145.   for (i = 0; i < wind; i++)
  2146.     free (words[i]);
  2147.   for (i = wind + 1; words[i]; i++)
  2148.     free (words[i]);
  2149.   free (words);
  2150.   return s;
  2151. }
  2152.  
  2153. #if defined (STATIC_MALLOC)
  2154.  
  2155. /* **************************************************************** */
  2156. /*                                    */
  2157. /*            xmalloc and xrealloc ()                     */
  2158. /*                                    */
  2159. /* **************************************************************** */
  2160.  
  2161. static void memory_error_and_abort ();
  2162.  
  2163. static char *
  2164. xmalloc (bytes)
  2165.      int bytes;
  2166. {
  2167.   char *temp = (char *)malloc (bytes);
  2168.  
  2169.   if (!temp)
  2170.     memory_error_and_abort ();
  2171.   return (temp);
  2172. }
  2173.  
  2174. static char *
  2175. xrealloc (pointer, bytes)
  2176.      char *pointer;
  2177.      int bytes;
  2178. {
  2179.   char *temp;
  2180.  
  2181.   if (!pointer)
  2182.     temp = (char *)xmalloc (bytes);
  2183.   else
  2184.     temp = (char *)realloc (pointer, bytes);
  2185.  
  2186.   if (!temp)
  2187.     memory_error_and_abort ();
  2188.  
  2189.   return (temp);
  2190. }
  2191.  
  2192. static void
  2193. memory_error_and_abort ()
  2194. {
  2195.   fprintf (stderr, "history: Out of virtual memory!\n");
  2196.   abort ();
  2197. }
  2198. #endif /* STATIC_MALLOC */
  2199.  
  2200. /* **************************************************************** */
  2201. /*                                    */
  2202. /*                Test Code                */
  2203. /*                                    */
  2204. /* **************************************************************** */
  2205. #ifdef TEST
  2206. main ()
  2207. {
  2208.   char line[1024], *t;
  2209.   int done = 0;
  2210.  
  2211.   line[0] = 0;
  2212.  
  2213.   while (!done)
  2214.     {
  2215.       fprintf (stdout, "history%% ");
  2216.       t = gets (line);
  2217.  
  2218.       if (!t)
  2219.     strcpy (line, "quit");
  2220.  
  2221.       if (line[0])
  2222.     {
  2223.       char *expansion;
  2224.       int result;
  2225.  
  2226.       using_history ();
  2227.  
  2228.       result = history_expand (line, &expansion);
  2229.       strcpy (line, expansion);
  2230.       free (expansion);
  2231.       if (result)
  2232.         fprintf (stderr, "%s\n", line);
  2233.  
  2234.       if (result < 0)
  2235.         continue;
  2236.  
  2237.       add_history (line);
  2238.     }
  2239.  
  2240.       if (strcmp (line, "quit") == 0) done = 1;
  2241.       if (strcmp (line, "save") == 0) write_history (0);
  2242.       if (strcmp (line, "read") == 0) read_history (0);
  2243.       if (strcmp (line, "list") == 0)
  2244.     {
  2245.       register HIST_ENTRY **the_list = history_list ();
  2246.       register int i;
  2247.  
  2248.       if (the_list)
  2249.         for (i = 0; the_list[i]; i++)
  2250.           fprintf (stdout, "%d: %s\n", i + history_base, the_list[i]->line);
  2251.     }
  2252.       if (strncmp (line, "delete", strlen ("delete")) == 0)
  2253.     {
  2254.       int which;
  2255.       if ((sscanf (line + strlen ("delete"), "%d", &which)) == 1)
  2256.         {
  2257.           HIST_ENTRY *entry = remove_history (which);
  2258.           if (!entry)
  2259.         fprintf (stderr, "No such entry %d\n", which);
  2260.           else
  2261.         {
  2262.           free (entry->line);
  2263.           free (entry);
  2264.         }
  2265.         }
  2266.       else
  2267.         {
  2268.           fprintf (stderr, "non-numeric arg given to `delete'\n");
  2269.         }
  2270.     }
  2271.     }
  2272. }
  2273.  
  2274. #endif /* TEST */
  2275.  
  2276. /*
  2277. * Local variables:
  2278. * compile-command: "gcc -g -DTEST -o history history.c"
  2279. * end:
  2280. */
  2281.